import os
from typing import Annotated
from uuid import uuid4

from fastapi import APIRouter, Depends, UploadFile, File
from requests import Session
from starlette.responses import JSONResponse

import models
from auth import get_current_active_user
from db import SessionLocal, get_db
from schemas import ProductPublic

router = APIRouter(prefix="/api/product", tags=["产品"])

storage_path = os.path.join(os.getcwd(), 'storage/product')
if not os.path.exists(storage_path):
    os.makedirs(storage_path)




@router.post("/add")
async def add_product_with_image(current_user: Annotated[models.User, Depends(get_current_active_user)],name: str,model:str,color:str,spec:str, price:int, description: str, image: UploadFile = File(None), db: Session = Depends(get_db)):
    unique_id = uuid4()
    if image:
        file_extension = os.path.splitext(image.filename)[1]
        unique_filename = f"{unique_id}{file_extension}"
        file_path = os.path.join(storage_path, unique_filename)
        with open(file_path, "wb") as buffer:
            buffer.write(await image.read())
        image_path = f"storage/product/{unique_filename}"
    else:
        image_path = None
    product = models.Product(name=name, price=price, image=image_path, description=description, model=model,color=color,spec=spec)
    db.add(product)
    db.commit()
    db.refresh(product)
    data=ProductPublic.from_orm(product)
    return JSONResponse(data)

